package com.eshop.modules.template.service.impl;

import java.lang.invoke.SerializedLambda;
import com.eshop.api.BusinessException;
import com.eshop.modules.template.service.dto.RegionInfoDto;
import com.eshop.modules.template.domain.ShippingTemplatesRegion;
import java.util.Collection;
import java.math.BigDecimal;
import com.eshop.modules.template.service.dto.RegionChildrenDto;
import com.eshop.modules.template.service.dto.RegionDto;
import cn.hutool.core.util.IdUtil;
import com.eshop.modules.template.service.dto.AppointInfoDto;
import com.eshop.modules.template.domain.ShippingTemplatesFree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.io.IOException;
import java.util.Iterator;
import com.eshop.utils.FileUtil;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.modules.template.service.dto.YxShippingTemplatesDto;
import java.util.LinkedHashMap;
import java.util.List;
import com.github.pagehelper.PageInfo;
import java.util.Map;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.template.service.dto.ShippingTemplatesQueryCriteria;
import com.alibaba.fastjson.JSON;
import cn.hutool.core.bean.BeanUtil;
import com.eshop.api.EshopException;
import com.eshop.enums.ShopCommonEnum;
import com.eshop.modules.template.service.dto.ShippingTemplatesDto;
import com.eshop.modules.template.service.ShippingTemplatesFreeService;
import com.eshop.modules.template.service.ShippingTemplatesRegionService;
import com.eshop.dozer.service.IGenerator;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.modules.template.service.ShippingTemplatesService;
import com.eshop.modules.template.domain.ShippingTemplates;
import com.eshop.modules.template.service.mapper.ShippingTemplatesMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class ShippingTemplatesServiceImpl extends BaseServiceImpl<ShippingTemplatesMapper, ShippingTemplates> implements ShippingTemplatesService
{
    private final IGenerator generator;
    private final ShippingTemplatesRegionService shippingTemplatesRegionService;
    private final ShippingTemplatesFreeService shippingTemplatesFreeService;
    
    public void addAndUpdate(final Integer id, final ShippingTemplatesDto shippingTemplatesDto) {
        if (ShopCommonEnum.ENABLE_1.getValue().equals(shippingTemplatesDto.getAppoint()) && shippingTemplatesDto.getAppointInfo().isEmpty()) {
            throw new EshopException("请指定包邮地区");
        }
        final ShippingTemplates shippingTemplates = new ShippingTemplates();
        BeanUtil.copyProperties(shippingTemplatesDto, shippingTemplates, new String[0]);
        shippingTemplates.setRegionInfo(JSON.toJSONString(shippingTemplatesDto.getRegionInfo()));
        shippingTemplates.setAppointInfo(JSON.toJSONString(shippingTemplatesDto.getAppointInfo()));
        if (id != null && id > 0) {
            shippingTemplates.setId(id);
            this.updateById(shippingTemplates);
        }
        else {
            this.save(shippingTemplates);
        }
        this.saveRegion(shippingTemplatesDto, shippingTemplates.getId());
        this.saveFreeReigion(shippingTemplatesDto, shippingTemplates.getId());
    }
    
    public Map<String, Object> queryAll(final ShippingTemplatesQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<ShippingTemplates> page = (PageInfo<ShippingTemplates>)new PageInfo((List)this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", this.generator.convert(page.getList(), (Class)YxShippingTemplatesDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<ShippingTemplates> queryAll(final ShippingTemplatesQueryCriteria criteria) {
        return (this.baseMapper).selectList(QueryHelpPlus.getPredicate(ShippingTemplates.class, criteria));
    }
    
    public void download(final List<YxShippingTemplatesDto> all, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final YxShippingTemplatesDto yxShippingTemplates : all) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("模板名称", yxShippingTemplates.getName());
            map.put("计费方式", yxShippingTemplates.getType());
            map.put("地域以及费用", yxShippingTemplates.getRegionInfo());
            map.put("指定包邮开关", yxShippingTemplates.getAppoint());
            map.put("指定包邮内容", yxShippingTemplates.getAppointInfo());
            map.put("添加时间", yxShippingTemplates.getCreateTime());
            map.put(" updateTime", yxShippingTemplates.getUpdateTime());
            map.put(" isDel", yxShippingTemplates.getIsDel());
            map.put("排序", yxShippingTemplates.getSort());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    private void saveFreeReigion(final ShippingTemplatesDto yxShippingTemplates, final Integer tempId) {
        if (yxShippingTemplates.getAppointInfo() == null || yxShippingTemplates.getAppointInfo().isEmpty()) {
            return;
        }
        final int count = this.shippingTemplatesFreeService.count((Wrapper)Wrappers.<ShippingTemplatesFree>lambdaQuery().eq(ShippingTemplatesFree::getTempId, tempId));
        if (count > 0) {
            this.shippingTemplatesFreeService.remove((Wrapper)Wrappers.<ShippingTemplatesFree>lambdaQuery().eq(ShippingTemplatesFree::getTempId, tempId));
        }
        final List<ShippingTemplatesFree> shippingTemplatesFrees = new ArrayList<ShippingTemplatesFree>();
        final List<AppointInfoDto> appointInfo = yxShippingTemplates.getAppointInfo();
        for (final AppointInfoDto appointInfoDto : appointInfo) {
            final String uni = IdUtil.simpleUUID();
            if (appointInfoDto.getPlace() != null && !appointInfoDto.getPlace().isEmpty()) {
                for (final RegionDto regionDto : appointInfoDto.getPlace()) {
                    if (regionDto.getChildren() != null && !regionDto.getChildren().isEmpty()) {
                        for (final RegionChildrenDto childrenDto : regionDto.getChildren()) {
                            final ShippingTemplatesFree shippingTemplatesFree = ShippingTemplatesFree.builder().tempId(tempId).number(new BigDecimal(appointInfoDto.getA_num())).price(new BigDecimal(appointInfoDto.getA_price())).type(yxShippingTemplates.getType()).uniqid(uni).provinceId(Integer.valueOf(regionDto.getCity_id())).cityId(Integer.valueOf(childrenDto.getCity_id())).build();
                            shippingTemplatesFrees.add(shippingTemplatesFree);
                        }
                    }
                }
            }
        }
        if (shippingTemplatesFrees.isEmpty()) {
            throw new EshopException("请添加包邮区域");
        }
        this.shippingTemplatesFreeService.saveBatch((Collection)shippingTemplatesFrees);
    }
    
    private void saveRegion(final ShippingTemplatesDto yxShippingTemplates, final Integer tempId) {
        final int count = this.shippingTemplatesRegionService.count((Wrapper)Wrappers.<ShippingTemplatesRegion>lambdaQuery().eq(ShippingTemplatesRegion::getTempId, tempId));
        if (count > 0) {
            this.shippingTemplatesRegionService.remove((Wrapper)Wrappers.<ShippingTemplatesRegion>lambdaQuery().eq(ShippingTemplatesRegion::getTempId, tempId));
        }
        final List<ShippingTemplatesRegion> shippingTemplatesRegions = new ArrayList<ShippingTemplatesRegion>();
        final List<RegionInfoDto> regionInfo = yxShippingTemplates.getRegionInfo();
        for (final RegionInfoDto regionInfoDto : regionInfo) {
            final String uni = IdUtil.simpleUUID();
            if (regionInfoDto.getRegion() != null && !regionInfoDto.getRegion().isEmpty()) {
                for (final RegionDto regionDto : regionInfoDto.getRegion()) {
                    if (regionDto.getChildren() != null && !regionDto.getChildren().isEmpty()) {
                        for (final RegionChildrenDto childrenDtp : regionDto.getChildren()) {
                            final ShippingTemplatesRegion shippingTemplatesRegion = ShippingTemplatesRegion.builder().tempId(tempId).first(new BigDecimal(regionInfoDto.getFirst())).firstPrice(new BigDecimal(regionInfoDto.getPrice())).continues(new BigDecimal(regionInfoDto.get_continue())).continuePrice(new BigDecimal(regionInfoDto.getContinue_price())).type(yxShippingTemplates.getType()).uniqid(uni).provinceId(Integer.valueOf(regionDto.getCity_id())).cityId(Integer.valueOf(childrenDtp.getCity_id())).build();
                            shippingTemplatesRegions.add(shippingTemplatesRegion);
                        }
                    }
                    else {
                        final ShippingTemplatesRegion shippingTemplatesRegion2 = ShippingTemplatesRegion.builder().tempId(tempId).first(new BigDecimal(regionInfoDto.getFirst())).firstPrice(new BigDecimal(regionInfoDto.getPrice())).continues(new BigDecimal(regionInfoDto.get_continue())).continuePrice(new BigDecimal(regionInfoDto.getContinue_price())).type(yxShippingTemplates.getType()).uniqid(uni).provinceId(Integer.valueOf(regionDto.getCity_id())).build();
                        shippingTemplatesRegions.add(shippingTemplatesRegion2);
                    }
                }
            }
        }
        if (shippingTemplatesRegions.isEmpty()) {
            throw new BusinessException("请添加区域");
        }
        this.shippingTemplatesRegionService.saveBatch((Collection)shippingTemplatesRegions);
    }
    
    public ShippingTemplatesServiceImpl(final IGenerator generator, final ShippingTemplatesRegionService shippingTemplatesRegionService, final ShippingTemplatesFreeService shippingTemplatesFreeService) {
        this.generator = generator;
        this.shippingTemplatesRegionService = shippingTemplatesRegionService;
        this.shippingTemplatesFreeService = shippingTemplatesFreeService;
    }
}
